# coding=utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf8')
import socket
import threading
import utils
import json


logger = utils.get_logger(__name__)


class GoBangServer(object):
    def __init__(self):
        logger.info(u'正在初始化服务器...')
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind(('0.0.0.0', 9887))
        self.cheesboard_size = utils.CHESSBOARD_SIZE  # 棋盘尺寸，这里采用标准的15*15
        self.cheesboard = [[0 for i in range(self.cheesboard_size)] for j in range(self.cheesboard_size)]  # 初始化一个全为0的棋盘
        self.need_ui = 0  # 是否需要ui参与 0-不需要ui参与 1-需要ui参与
        self.server_mode = 1  # 服务器模式 0-等待选择 1-通过ui选择 2-人机对战 3-AI训练
        self.ui_cilent_thread = None
        self.ai_client_thread = None
        self.ai_client_thread_1 = None
        self.ai_client_thread_2 = None
        self.server.listen(5)
        self.wait_connect()

    def wait_connect(self):
        """
        等待客户端进行连接
        :return:
        """
        logger.info(u'等待客户端连接...')
        if self.server_mode == 1:  # 等待ui进行连接
            self.connect_mode_1()
        elif self.server_mode == 2:
            self.connect_mode_2()
        elif self.server_mode == 3:
            self.connect_mode_3()


    def connect_mode_1(self):
        """
        当服务器处于模式1下的连接形式
        :return:
        """
        sock, addr = self.server.accept()
        data = sock.recv(1024)
        logger.info(u'data:{}'.format(data))
        if 'ui-client' in data:
            logger.info(u'图形化界面客户端已连接')
            self.ui_cilent_thread = threading.Thread(target=self.deal_with_ui_client, args=(sock, addr))
            self.ui_cilent_thread.start()

    def connect_mode_2(self):
        """
        当服务器处于模式2下的连接形式
        :return:
        """
        for i in range(2):
            sock, addr = self.server.accept()
            data = sock.recv(1024)
            if 'ui-client' in data:
                logger.info(u'图形化界面客户端已连接')
                self.ui_cilent_thread = threading.Thread(target=self.deal_with_ui_client, args=(sock, addr))
                self.ui_cilent_thread.start()
            elif 'ai-client' in data:
                logger.info(u'五子棋AI已连接')
                self.ai_client_thread = threading.Thread(target=self.deal_with_ai_client, args=(sock, addr))
                self.ai_client_thread.start()

    def connect_mode_3(self):
        """
        当服务器处于模式3下的连接形式
        :return:
        """
        for i in range(3):
            sock, addr = self.server.accept()
            data = sock.recv(1024)
            if 'ui-client' in data:
                logger.info(u'图形化界面客户端已连接')
                self.ui_cilent_thread = threading.Thread(target=self.deal_with_ui_client, args=(sock, addr))
                self.ui_cilent_thread.start()
            elif 'ai-client-1' in data:
                logger.info(u'五子棋AI-1(正常AI)已连接')
                self.ai_client_thread = threading.Thread(target=self.deal_with_ai_client_1, args=(sock, addr))
                self.ai_client_thread.start()
            elif 'ai-client-2' in data:
                logger.info(u'五子棋AI-2(扰动AI)已连接')
                self.ai_client_thread = threading.Thread(target=self.deal_with_ai_client_2, args=(sock, addr))
                self.ai_client_thread.start()


    def deal_with_ui_client(self,sock,addr):
        """
        与GUI进行交互
        :param sock:socket连接
        :param addr: ip地址
        :return:
        """
        self.agent_1=1
        self.agent_2=-1
        self.current_chees_agent=self.agent_1
        self.chees_flag=0 # 0-初始态 1-轮到agent1下棋 2-agent1下棋完毕 3-轮到agent2下棋 4-agent2下棋完毕 5-产生胜负，等待开始
        while True:
            self.chees_flag=1#轮到1下棋
            js_data={'command':'start_game','x':12,'y':12,'color':self.current_chees_agent}
            sock.send(json.dumps(js_data))
            self.chees_flag=2#1下棋完毕
            while True:
                self.chees_flag=(self.chees_flag+1)%5

    def get_chees_pos(self):
        pass

    def deal_with_ai_client(self,sock,addr):
        pass

    def deal_with_ai_client_1(self,sock,addr):
        pass

    def deal_with_ai_client_2(self,sock,addr):
        pass


if __name__ == '__main__':
    GoBangServer()